import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:library_base/entities/enum_entity.dart';
import 'package:library_base/ext/bool_ext.dart';
import 'package:library_base/ext/string_ext.dart';
import 'package:library_base/utils/get_util.dart';
import 'package:library_base/utils/num_util.dart';
import 'package:library_base/constant/constant.dart';
import 'package:library_base/entities/goods_child_entity.dart';
import 'package:library_base/entities/goods_child_info_entity.dart';
import 'package:library_base/ext/theme_data_ext.dart';
import 'package:library_base/global/multi_language.dart';
import 'package:library_base/res/gaps.dart';
import 'package:library_base/res/styles.dart';
import 'package:library_base/route/routers.dart';
import 'package:library_base/utils/sp_util.dart';
import 'package:library_base/utils/theme_util.dart';
import 'package:library_base/utils/toast_util.dart';
import 'package:library_base/utils/widget_generate_util.dart';
import 'package:library_base/widget/button/gradient_button.dart';
import 'package:library_base/ext/double_ext.dart';

class AddGoodsInfoDialog extends StatefulWidget {
  const AddGoodsInfoDialog({
    Key? key,
  }) : super(key: key);

  @override
  State<AddGoodsInfoDialog> createState() => _AddGoodsInfoDialogState();
}

class _AddGoodsInfoDialogState extends State<AddGoodsInfoDialog> {
  ///采购数量
  final TextEditingController purchaseQuantityController = TextEditingController();
  final FocusNode purchaseQuantityFocusNode = FocusNode();

  ///采购单价
  final TextEditingController purchasePricesController = TextEditingController();

  final FocusNode purchasePricesFocusNode = FocusNode();

  ///采购重量
  final TextEditingController purchaseWeightController = TextEditingController();
  final FocusNode purchaseWeightFocusNode = FocusNode();

  ///采购金额
  final TextEditingController purchaseAmountController = TextEditingController();
  final FocusNode purchaseAmountFocusNode = FocusNode();

  ///服务费
  final TextEditingController serviceChargeController = TextEditingController();
  final FocusNode serviceChargeFocusNode = FocusNode();

  ///是否单头录入
  bool isSingleHeadEntry = false;

  void Function(
    GoodsChildEntity,
    GoodsChildEntity,
    int,
  )? callback;

  late GoodsChildEntity temporaryGoodsChildEntity;

  late GoodsChildEntity originalGoodsChildEntity;

  int index = 0;

  @override
  void initState() {
    super.initState();
    var arguments = Get.arguments;
    callback = arguments['CallBack'];
    index = arguments['index'];
    temporaryGoodsChildEntity = arguments['Goods'];
    originalGoodsChildEntity = arguments['OriginalGoods'];
    isSingleHeadEntry = originalGoodsChildEntity.singleEntry;
    purchaseQuantityController.text = originalGoodsChildEntity.totalCount.isNotZeroAndNull()
        ? originalGoodsChildEntity.totalCount.toString()
        : '';

    if (originalGoodsChildEntity.unit == ServiceUnit.JIN.name) {
      if (originalGoodsChildEntity.price.isNotZeroAndNull()) {
        if (SPUtil.isJin) {
          purchasePricesController.text = originalGoodsChildEntity.price.toString();
        } else {
          purchasePricesController.text = NumUtil.multiply(originalGoodsChildEntity.price!, 2).toString();
        }
      } else {
        purchasePricesController.text = '';
      }
    } else {
      if (SPUtil.isJin) {
        purchasePricesController.text = originalGoodsChildEntity.price.isNotZeroAndNull()
            ? (NumUtil.divide(originalGoodsChildEntity.price!, 2)).toString()
            : '';
      } else {
        purchasePricesController.text = originalGoodsChildEntity.price.isNotZeroAndNull()
            ? originalGoodsChildEntity.price.toString()
            : '';
      }
    }

    purchaseWeightController.text = originalGoodsChildEntity.totalWeight.isNotZeroAndNull()
        ? originalGoodsChildEntity.totalWeight.remoteUnitTransitionLocalUnitStr(originalGoodsChildEntity.unit)
        : '';

    purchaseAmountController.text = originalGoodsChildEntity.purchaseAmount.isNotZeroAndNull()
        ? originalGoodsChildEntity.purchaseAmount.toString()
        : '';

    serviceChargeController.text = originalGoodsChildEntity.serviceCost.isNotZeroAndNull()
        ? originalGoodsChildEntity.serviceCost.toString()
        : '';

    if (isSingleHeadEntry) {
      double totalPurchaseWeight = 0.0;
      for (int i = 0; i < originalGoodsChildEntity.goodsDetails.length; i++) {
        GoodsChildInfoEntity goodsChildInfoEntity = originalGoodsChildEntity.goodsDetails[i];
        totalPurchaseWeight = NumUtil.add(totalPurchaseWeight, goodsChildInfoEntity.weight);
      }
      purchaseWeightController.text =
          totalPurchaseWeight <= 0.0 ? "" : totalPurchaseWeight.remoteUnitTransitionLocalUnitStr(originalGoodsChildEntity.unit);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: true,
      backgroundColor: Colors.transparent,
      body: SingleChildScrollView(
        child: Stack(
          children: [
            Column(
              children: [
                SizedBox(height: 188.w / 2 + 0.05.sh),
                Row(
                  children: [
                    SizedBox(width: 0.1.sw),
                    Container(
                      padding: EdgeInsets.only(right: 36.w, left: 36.w, bottom: 36.w),
                      width: 0.8.sw,
                      height: 0.75.sh,
                      decoration: BoxDecoration(
                        color: ThemeUtil.getTheme().colorScheme.secondary,
                        borderRadius: const BorderRadius.all(Radius.circular(15)),
                        boxShadow: [
                          BoxShadow(
                            color: Colors.black.withOpacity(0.1), // 阴影的颜色
                            offset: const Offset(0, 0), // 阴影与容器的距离
                            blurRadius: 10.0, // 高斯的标准偏差与盒子的形状卷积。
                            spreadRadius: 0.0, // 在应用模糊之前，框应该膨胀的量。
                          ),
                        ],
                      ),
                      child: Column(
                        children: [
                          Visibility(visible: false, child: SizedBox(height: 188.w / 2 + 36.w)),
                          gapH46,
                          Text(originalGoodsChildEntity.goodsName,
                              style: TextStyles.textBoldBlack36),
                          Gaps.vwGap18,
                          Expanded(
                              child: SingleChildScrollView(
                            physics: const BouncingScrollPhysics(),
                            child: SizedBox(
                              width: double.infinity,
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Gaps.vhGap36,
                                  GenerateWidgetUtil.inputRichText(MultiLanguage.purchaseQuantity.tr +
                                      (originalGoodsChildEntity.singleEntry
                                          ? ''
                                          : " (${originalGoodsChildEntity.standardWeight.remoteUnitTransitionLocalUnitStr(originalGoodsChildEntity.unit)}${SPUtil.isJin.unitStrZh()}/${MultiLanguage.part.tr})")),
                                  Gaps.v_w_Gap24,
                                  GenerateWidgetUtil.inputInfo(
                                      inputFormatters: isSingleHeadEntry
                                          ? [FilteringTextInputFormatter.digitsOnly]
                                          : [FilteringTextInputFormatter.allow(RegExp("[0-9.]"))],
                                      hintText: MultiLanguage.enterPurchaseQuantity.tr,
                                      // enabled: isSingleHeadEntry,
                                      enabled: true,
                                      controller: purchaseQuantityController,
                                      focusNode: purchaseQuantityFocusNode,
                                      onChanged: _goodsCountChange),
                                  Gaps.v_w_Gap24,
                                  GenerateWidgetUtil.inputRichText(MultiLanguage.purchasePrices.tr),
                                  Gaps.v_w_Gap24,
                                  GenerateWidgetUtil.inputInfo(
                                      // unit: originalGoodsChildEntity.unit == 'JIN'
                                      //     ? (SPUtil.isJin
                                      //         ? Messages.yuanJin.tr
                                      //         : Messages.yuanGongJin.tr)
                                      //     : Messages.yuanFen.tr,
                                      unit:originalGoodsChildEntity.unit.getUnitStr(),
                                      hintText: MultiLanguage.enterPurchasePrice.tr,
                                      controller: purchasePricesController,
                                      focusNode: purchasePricesFocusNode,
                                      onChanged: _calculatePurchaseAmount),
                                  Gaps.v_w_Gap24,
                                  GenerateWidgetUtil.inputRichText(MultiLanguage.purchaseWeight.tr +
                                      SPUtil.isJin.unitStrZhWithBracket()),
                                  Gaps.v_w_Gap24,
                                  Container(
                                    constraints: BoxConstraints.expand(height: 90.w),
                                    child: Row(children: [
                                      Expanded(
                                        child: GenerateWidgetUtil.inputInfo(
                                            onChanged: _calculatePurchaseAmount,
                                            controller: purchaseWeightController,
                                            focusNode: purchaseWeightFocusNode,
                                            unit: SPUtil.isJin.unitStrZh(),
                                            enabled: !isSingleHeadEntry &&
                                                originalGoodsChildEntity.singleEntry,
                                            hintText: _singleText1(MultiLanguage.enterPurchaseWeight.tr),
                                            borderRadius: isSingleHeadEntry
                                                ? const BorderRadius.only(
                                                    topLeft: Radius.circular(6.0),
                                                    bottomLeft: Radius.circular(6.0),
                                                  )
                                                : const BorderRadius.all(Radius.circular(6.0))),
                                      ),
                                      Visibility(
                                        visible: isSingleHeadEntry,
                                        child: const SizedBox(
                                          width: 2,
                                        ),
                                      ),
                                      Visibility(
                                        visible: isSingleHeadEntry,
                                        child: GestureDetector(
                                          onTap: _singleEntry,
                                          child: GenerateWidgetUtil.roundOrangeWidget(
                                              child: Container(
                                            alignment: Alignment.center,
                                            width: 150.w,
                                            child: Text(MultiLanguage.singleEntry.tr,
                                                style: TextStyles.textWhite28),
                                          )),
                                        ),
                                      ),
                                    ]),
                                  ),
                                  Gaps.v_w_Gap24,
                                  GenerateWidgetUtil.inputRichText(MultiLanguage.purchaseAmount.tr),
                                  Gaps.v_w_Gap24,
                                  GenerateWidgetUtil.inputInfo(
                                    controller: purchaseAmountController,
                                    focusNode: purchaseAmountFocusNode,
                                    unit: MultiLanguage.yuan.tr,
                                    enabled: false,
                                    hintText: MultiLanguage.automaticCalculation.tr,
                                  ),
                                  Gaps.v_w_Gap24,
                                  GenerateWidgetUtil.inputRichText(MultiLanguage.serviceCharge.tr,
                                      prefix: ""),
                                  Gaps.v_w_Gap24,
                                  GenerateWidgetUtil.inputInfo(
                                    controller: serviceChargeController,
                                    focusNode: serviceChargeFocusNode,
                                    unit: MultiLanguage.yuan.tr,
                                    enabled: !isSingleHeadEntry,
                                    hintText: _singleText(MultiLanguage.enterServiceFee.tr),
                                  ),
                                ],
                              ),
                            ),
                          )),
                          Row(
                            children: [
                              Expanded(
                                child: GradientButton(
                                  ThemeUtil.getTheme(),
                                  radius: const BorderRadius.only(
                                      topLeft: Radius.circular(50),
                                      bottomLeft: Radius.circular(50)),
                                  colors: ThemeUtil.getTheme().buttonLeft1BgColor(),
                                  height: 80.w,
                                  text: MultiLanguage.cancel.tr,
                                  onPressed: _cancel,
                                ),
                              ),
                              Expanded(
                                child: GradientButton(
                                  ThemeUtil.getTheme(),
                                  radius: const BorderRadius.only(
                                      topRight: Radius.circular(50),
                                      bottomRight: Radius.circular(50)),
                                  height: 80.w,
                                  colors: ThemeUtil.getTheme().buttonRight1BgColor(),
                                  text: MultiLanguage.save.tr,
                                  onPressed: save,
                                ),
                              ),
                            ],
                          )
                        ],
                      ),
                    ),
                    SizedBox(width: 0.1.sw),
                  ],
                ),
              ],
            ),
            Visibility(
              visible: false,
              child: Column(
                mainAxisSize: MainAxisSize.max,
                children: [
                  SizedBox(height: 0.05.sh),
                  Row(
                    mainAxisSize: MainAxisSize.max,
                    children: [
                      SizedBox(width: (1.sw - 188.w) / 2),
                      Container(
                        width: 188.w,
                        height: 188.w,
                        decoration: BoxDecoration(
                          color: ThemeUtil.getTheme().colorScheme.secondary,
                          borderRadius: const BorderRadius.all(Radius.circular(15)),
                          boxShadow: [
                            BoxShadow(
                              color: Colors.black.withOpacity(0.3), // 阴影的颜色
                              offset: const Offset(0, 0), // 阴影与容器的距离
                              blurRadius: 20.0, // 高斯的标准偏差与盒子的形状卷积。
                              spreadRadius: 0.0, // 在应用模糊之前，框应该膨胀的量。
                            ),
                          ],
                        ),
                        clipBehavior: Clip.hardEdge,
                        child: CachedNetworkImage(
                          imageUrl: Constant.placeholderImg,
                        ),
                      ),
                      SizedBox(width: (1.sw - 188.w) / 2),
                    ],
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  ///录入单头
  void _singleEntry() async {
    if (!NumUtil.isNumber(purchaseQuantityController.text)) {
      ToastUtil.normal(MultiLanguage.pleaseEnterPurchaseQuantity.tr);
      return;
    }
    double quantity = double.parse(purchaseQuantityController.text);
    int quantityInt = quantity.toInt();
    quantityInt = quantity - quantityInt > 0 ? quantityInt + 1 : quantityInt;
    var arguments = <String, dynamic>{};
    arguments['ItemCount'] = quantityInt;
    arguments['GoodsChildInfoEntity'] = <GoodsChildInfoEntity>[];

    var temporary = List<GoodsChildInfoEntity>.generate(
        temporaryGoodsChildEntity.goodsDetails.length, (int index) {
      return temporaryGoodsChildEntity.goodsDetails[index];
    }, growable: true);

    Get.toNamed(Routers.singleHeadEntryPage, preventDuplicates: false, arguments: {
      'ItemCount': quantityInt,
      'unit': temporaryGoodsChildEntity.unit,
      'GoodsChildInfoEntity': temporary,
      'callbackGoodsChildInfoEntity': _callbackGoodsChildInfoList,
    });
  }

  _callbackGoodsChildInfoList(List<GoodsChildInfoEntity>? list) {
    temporaryGoodsChildEntity.goodsDetails = list ?? [];
    autoCalculate();
  }

  //自动计算
  autoCalculate() {
    if (isSingleHeadEntry) {
      double totalWeight = 0.0;
      double purchaseAmount = 0.0;
      double serviceCharge = 0.0;
      for (var element in temporaryGoodsChildEntity.goodsDetails) {
        totalWeight = NumUtil.add(totalWeight, element.weight.numAsUnit());
        serviceCharge = NumUtil.add(serviceCharge, element.serviceCost);
      }
      var isCanCalculate = NumUtil.isNumber(purchasePricesController.text);
      if (isCanCalculate) {
        double unitPrice = double.parse(purchasePricesController.text);
        purchaseAmount = NumUtil.multiply(unitPrice, totalWeight);
        purchaseAmountController.text =
            purchaseAmount != 0.0 ? NumUtil.formatNum(purchaseAmount) : "";
      }
      purchaseWeightController.text = totalWeight != 0.0 ? totalWeight.toString() : "";
      serviceChargeController.text = serviceCharge != 0.0 ? serviceCharge.toString() : "";
      setState(() {});
    } else {

      var purchaseQuantity = 0.0;
      // if (!temporaryGoodsChildEntity.singleEntry) {
        if (NumUtil.isNumber(purchaseQuantityController.text)) {
          purchaseQuantity = double.parse(purchaseQuantityController.text);
          purchaseWeightController.text = (purchaseQuantity * temporaryGoodsChildEntity.standardWeight!.remoteUnitTransitionLocalUnit(temporaryGoodsChildEntity.unit)).toString();
        } else {
          purchaseWeightController.text = '';
        }
      // }
      double purchaseAmount = 0;
      var isCanCalculate = NumUtil.isNumber(purchaseWeightController.text) &&
          NumUtil.isNumber(purchasePricesController.text);
      if (isCanCalculate) {
        double unitPrice = double.parse(purchasePricesController.text);
        double totalWeight = double.parse(purchaseWeightController.text);
        // if (temporaryGoodsChildEntity.singleEntry) {
          purchaseAmount = NumUtil.multiply(unitPrice, totalWeight);
        // } else {
        //   purchaseAmount = NumUtil.multiply(unitPrice, purchaseQuantity);
        // }
        purchaseAmountController.text =
            purchaseAmount != 0.0 ? NumUtil.formatNum(purchaseAmount) : "";
      } else {
        purchaseAmountController.text = '';
      }
      setState(() {});
    }
  }

  ///确定保存
  void save() async {
    if (!NumUtil.isNumber(purchaseQuantityController.text)) {
      ToastUtil.normal(MultiLanguage.pleaseEnterPurchaseQuantity.tr);
      return;
    }

    temporaryGoodsChildEntity.totalCount = double.parse(purchaseQuantityController.text);
    if (!NumUtil.isNumber(purchasePricesController.text)) {
      ToastUtil.normal(MultiLanguage.pleaseEnterPurchasePrice.tr);
      return;
    }

    temporaryGoodsChildEntity.price = double.parse(purchasePricesController.text).localUnitToRemoteUnit(temporaryGoodsChildEntity.unit);

    if (!isSingleHeadEntry) {
      if (!NumUtil.isNumber(purchaseWeightController.text)) {
        ToastUtil.normal(MultiLanguage.pleaseEnterPurchaseWeight.tr);
        return;
      } else {
        var totalWeight = double.parse(purchaseWeightController.text);
        if (totalWeight == 0.0) {
          ToastUtil.normal(MultiLanguage.purchaseWeightCannotBe0.tr);
          return;
        }
      }
    } else {
      if (temporaryGoodsChildEntity.goodsDetails.isEmpty) {
        ToastUtil.normal(MultiLanguage.pleaseEnterSingleHeaderData.tr);
        return;
      }
    }

    temporaryGoodsChildEntity.totalWeight = purchaseWeightController.text.strAsUnitNum1(temporaryGoodsChildEntity.unit);

    temporaryGoodsChildEntity.serviceCost = NumUtil.isNumber(serviceChargeController.text)
        ? double.parse(serviceChargeController.text)
        : 0.0;
    callback!.call(
      originalGoodsChildEntity,
      temporaryGoodsChildEntity,
      index,
    );
    GetHelper.back();
  }

  ///返回自动计算或者文本参数
  String _singleText(String showText) {
    if (isSingleHeadEntry) {
      return MultiLanguage.automaticCalculation.tr;
    } else {
      return showText;
    }
  }

  ///返回自动计算或者文本参数
  String _singleText1(String showText) {
    if (!temporaryGoodsChildEntity.singleEntry) {
      return MultiLanguage.automaticCalculation.tr;
    }
    if (isSingleHeadEntry) {
      return MultiLanguage.automaticCalculation.tr;
    } else {
      return showText;
    }
  }

  _cancel() => GetHelper.back();

  ///计算采购金额和重量
  void _calculatePurchaseAmount(String value) {
    autoCalculate();
  }

  ///计算采购金额和重量
  void _goodsCountChange(String value) {
    if(isSingleHeadEntry){
      temporaryGoodsChildEntity.goodsDetails.clear();
    }
    autoCalculate();
  }

}
